package cn.huaqingcheng.tool.crypto.encrypt;

import cn.huaqingcheng.tool.crypto.codec.HexTool;
import org.jetbrains.annotations.NotNull;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES 对称加密
 *
 * @see <a href="https://developer.aliyun.com/article/901534">浅析五种最常用的Java加密算法 - 阿里云开发者社区</a>
 */
@SuppressWarnings("unused")
public interface AESTool {

    String AES = "AES";

    String AES_ECB = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     */
    static byte[] encode(String str, String pwd) {
        try {
            Cipher cipher = Cipher.getInstance(AES_ECB);
            cipher.init(Cipher.ENCRYPT_MODE, getKey(pwd));

            return cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用指定随机种子生成 key
     *
     * @param seed 随机种子
     */
    @SuppressWarnings("MagicNumber")
    @NotNull
    private static SecretKeySpec getKey(String seed) throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance(AES);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(seed.getBytes());
        generator.init(128, random);
        return new SecretKeySpec(generator.generateKey().getEncoded(), AES);
    }

    /**
     * 解密
     */
    static byte[] decode(String str, String pwd) {
        try {
            Cipher cipher = Cipher.getInstance(AES_ECB);
            cipher.init(Cipher.DECRYPT_MODE, getKey(pwd));
            byte[] content = HexTool.parseHex(str);

            return cipher.doFinal(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
